﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;

public partial class Pages_CreateMaster : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {


        Int32 roleId = 0;
        if (!Page.IsPostBack)
        {
            roleId = Convert.ToInt32(Session["RoleId"]);
            string pageType = "";
            if (Request.QueryString != null && Request.QueryString.Count > 0)
            {
                pageType = Request.QueryString[0].ToString();
                CallDisplayUser(pageType, roleId);

            }
        }

    }


    private void CallDisplayUser(string pageType, int roleId)
    {
        DataTable dt = null;
        switch (pageType)
        {
            case Constants.Challan:
                CallShowPageType(dvChallan);
                CallCreateChallanPage();
                break;
            case Constants.Company:
                CallShowPageType(PanComp);
                CallCreateCompanyPage();

                break;
            case Constants.Employee:
                CallShowPageType(dvEmployee);
                CallCreateEmployeePage();
                break;
            case Constants.Truck:
                CallShowPageType(dvTruck);
                CallCreateTruckPage();
                break;
            case Constants.Material:
                CallShowPageType(dvMaterial);
                CallCreateMaterialPage();
                break;
            case Constants.Bill:

                break;
            default:
                break;
        }
    }

    #region TruckDetails
    private void CallCreateTruckPage()
    {
        hdnVehicleId.Value = "0";
        if (Request.QueryString != null && Request.QueryString["TruckId"] != null)
        {
            hdnVehicleId.Value = Request.QueryString["TruckId"].ToString();
            CallUpdateModeTruck();
        }
    }
    private void CallUpdateModeTruck()
    {
        try
        {
            int vehicleId = Convert.ToInt32(hdnVehicleId.Value);
            DataTable dt = new DataTable();
            dt = BusinessClass.GetVehicleDetails(0, vehicleId);
            if (dt.Rows.Count == 1)
            {
                txtTruckNo.Text = Convert.ToString(dt.Rows[0]["VehicleNo"]);
                txtModelNo.Text = Convert.ToString(dt.Rows[0]["VehicleModel"]);
                txtPurchaseDate.Text = Convert.ToString(dt.Rows[0]["VehiclePurchaseDate"]);
                lblTruckStatus.Text = Convert.ToString(dt.Rows[0]["Status"]);
                btnCreateTruck.Text = "Update";
                trTrcukStatus.Visible = true;
            }
        }
        catch (Exception ex)
        {
            dvError.Visible = true;
            ltlError.Text = ex.Message;
        }
    }

    protected void btnCreateTruck_Click(object sender, EventArgs e)
    {
        try
        {
            int userId = 0;
            int vehicleId = 0;
            vehicleId = Convert.ToInt32(hdnVehicleId.Value);
            userId = Convert.ToInt32(Session["UserId"]);
            string dt = "";
            dt = Request.Form[txtPurchaseDate.UniqueID];
            int res = DataAccessClass.CreateVehicle(dt, txtModelNo.Text, txtTruckNo.Text, userId, vehicleId);
            if (res > 0)
            {
                trMessage.Visible = true;
            }
            else
            {
                trError.Visible = true;
                trMessage.Visible = false;
            }
        }
        catch (Exception ex)
        {
            dvError.Visible = true;
            ltlError.Text = ex.Message;
        }
    }
    #endregion

    #region EmployeeDetails
    private void CallCreateEmployeePage()
    {
        int emp = 0;

        hdnCOmpId.Value = "0";

        if (Request.QueryString != null && Request.QueryString.Count == 2)
        {
            emp = Convert.ToInt32(Request.QueryString["EmpId"].ToString());
            hdnCOmpId.Value = emp.ToString();
            CallUpdateModeEmployee(emp);

        }
    }

    private void CallUpdateModeEmployee(int empId)
    {
        try
        {
            DataTable dt = new DataTable();
            dt = BusinessClass.GetEmployeeDetails(0, empId);
            if (dt.Rows.Count == 1)
            {
                txtName.Text = Convert.ToString(dt.Rows[0]["EmployeeName"]); 
                txtEmpContact.Text = Convert.ToString(dt.Rows[0]["EmployeeContactNo"]); 
                txtEmpAddress.Text = Convert.ToString(dt.Rows[0]["EmployeeAddress"]); 
                txtEmpNo.Text = Convert.ToString(dt.Rows[0]["EmployeeNo"]); 
                lblEmpStatus.Text = Convert.ToString(dt.Rows[0]["Status"]);
                trEmpStatus.Visible = true;
                trLicence.Visible = true;
                trStatus.Visible = true;
                imgIDProof.ImageUrl = ImageURL1(empId.ToString(), "E", 1);
                imgLicence.ImageUrl = ImageURL(empId.ToString(), "E", 2);
               
                btnCreateEmp.Text = "Update";
            }
        }
        catch (Exception ex)
        {
            dvError.Visible = true;
            ltlError.Text = ex.Message;
        }
    }

    protected void btnCreateEmp_Click(object sender, EventArgs e)
    {
        try
        {
            CreateEMployee();
        }
        catch (Exception ex)
        {
            trError.InnerText = ex.Message;
        }
    }

    private void CreateEMployee()
    {
        try
        {
            int imgIdProfSize, imgLicenceSize;
            int userId = 0;
            Stream imageStream1, imageStream2;
            userId = Convert.ToInt32(Session["UserId"]);
            // Gets the Size of the Image
            imgIdProfSize = fldIDProof.PostedFile.ContentLength;
            imgLicenceSize = fldLicence.PostedFile.ContentLength;
            byte[] imageIdProof = new byte[imgIdProfSize];
            byte[] imageLicense = new byte[imgLicenceSize];
            int intStatus1, status2 = 0;
            imageStream1 = fldIDProof.PostedFile.InputStream;
            imageStream2 = fldLicence.PostedFile.InputStream;
            intStatus1 = imageStream1.Read(imageIdProof, 0, imgIdProfSize);
            status2 = imageStream2.Read(imageLicense, 0, imgLicenceSize);
            int res = DataAccessClass.CreateEmployee(hdnCOmpId.Value, txtName.Text, txtEmpNo.Text, txtEmpAddress.Text, txtEmpContact.Text, imageIdProof, imageLicense, userId);
            if (res > 0)
            {
                trMessage.Visible = true;
                trError.Visible = false;

            }
            else
            {
                trError.Visible = true;
                trMessage.Visible = false;
            }
            ltlError.Visible = false;
        }
        catch (Exception ex)
        {
            ltlError.Visible = true;
            dvError.Visible = true;
            ltlError.Text = ex.Message;
        }
    }


    #endregion

    #region CompanyDetails
    private void CallCreateCompanyPage()
    {
        int compId = 0;
        CallListCompanyType();
        if (Request.QueryString != null && Request.QueryString.Count == 2)
        {
            compId = Convert.ToInt32(Request.QueryString["CompId"].ToString());
            CallUpdateModeCompany(compId);

        }
        else
        {
            CallNewPageModeCompany();
        }
        hdnCOmpId.Value = compId.ToString();
    }
    private void CallNewPageModeCompany()
    {
        try
        {
        }
        catch (Exception ex)
        {
            dvError.Visible = true;
            ltlError.Text = ex.Message;
        }
    }
    private void CallUpdateModeCompany(int compId)
    {
        try
        {
            DataTable dt = new DataTable();
            dt = BusinessClass.GetCompanyDetails(0, compId);
            if (dt.Rows.Count == 1)
            {
              //  CallListCompanyType();
                ddlCompType.SelectedValue = dt.Rows[0]["CompanyType"].ToString();
                txtCompanyName.Text = Convert.ToString(dt.Rows[0]["CompanyName"]);
                txtAddress.Text = Convert.ToString(dt.Rows[0]["CompanyAddress"]);
                txtContactNo.Text = Convert.ToString(dt.Rows[0]["CompanyContact"]);
                txtEmail.Text = Convert.ToString(dt.Rows[0]["CompanyEmail"]);
                txtVat.Text = Convert.ToString(dt.Rows[0]["CompanyVatTIN"]);
                trCompImage.Visible = true;
                trCompStatus.Visible = true;
                imgCompLogo.ImageUrl = ImageURL(compId.ToString(), "C", 1);
                lblCompStatus.Text = Convert.ToString(dt.Rows[0]["Status"]);
                LoginButton.Text = "Update";
            }
        }
        catch (Exception ex)
        {
            dvError.Visible = true;
            ltlError.Text = ex.Message;
        }
    }
    private void CallListCompanyType()
    {
        DataSet dt = new DataSet();
        dt = BusinessClass.GetCompanyType();
        ddlCompType.DataSource = dt;
        ddlCompType.DataTextField = "Value";
        ddlCompType.DataValueField = "IndexKey";
        ddlCompType.DataBind();
    }
    protected void LoginButton_Click(object sender, EventArgs e)
    {
        try
        {
            CreateCompany();
        }
        catch (Exception ex)
        {
        }

    }
    private void CreateCompany()
    {
        try
        {
            int imageSize;
            string imageType;
            Stream imageStream;

            // Gets the Size of the Image
            imageSize = fldLogo.PostedFile.ContentLength;

            // Gets the Image Type
            imageType = fldLogo.PostedFile.ContentType;

            // Reads the Image stream
            imageStream = fldLogo.PostedFile.InputStream;

            byte[] imageContent = new byte[imageSize];
            int intStatus;
            intStatus = imageStream.Read(imageContent, 0, imageSize);
            int res = DataAccessClass.CreateCompany(hdnCOmpId.Value, ddlCompType.SelectedValue, txtCompanyName.Text, txtAddress.Text, txtContactNo.Text, txtEmail.Text, txtVat.Text, imageContent);
            if (res > 0)
            {
                trMessage.Visible = true;
                trError.Visible = false;
            }
            else
            {
                trError.Visible = true;
                trMessage.Visible = false;
            }
        }
        catch (Exception ex)
        {
            dvError.Visible = true;
            ltlError.Text = ex.Message;
        }
    }
    #endregion


    private void CallShowPageType(Panel pan)
    {
        pan.Visible = true;
    }

    public string ImageURL(string img_id, string type, int imgNo)
    {
        return ("GetImage.aspx?id=" + img_id + "&Type=" + type + "&ImageNo=" + imgNo);
    }

    public string ImageURL1(string img_id, string type, int imgNo)
    {
        return ("GetImage.aspx?id=" + img_id + "&Type=" + type + "&ImageNo=" + imgNo);
    }


    #region ChallanDetails
    private void CallCreateChallanPage()
    {
        int chId = 0;
        CallFillComboBoxes();
        if (Request.QueryString != null && Request.QueryString["ChId"] != null)
        {
            chId = Convert.ToInt32(Request.QueryString["ChId"].ToString());
            CallUpdateModeChallan(chId);
        }

        hdnChallanId.Value = chId.ToString();

    }


    private void CallUpdateModeChallan(int chId)
    {
        Challan ch = new Challan(chId, 0);
        trStatus.Visible = true;
        lblStatus.Text = ch.Status.ToString();
        ListItem itm ;//= new ListItem();
        txtDate.Text = ch.ChallanDate.ToString();
        itm = new ListItem();
        itm = ddlTransport.Items.FindByText(ch.TransComp.ToString());
        ddlTransport.SelectedValue = itm.Value;
       // ddlTransport.SelectedItem.Text = ch.TransComp.ToString();
        itm = new ListItem();
        itm = ddlSupplier.Items.FindByText(ch.SuppComp.ToString());
        ddlSupplier.SelectedValue = itm.Value;
       // ddlSupplier.SelectedItem.Text = ch.SuppComp.ToString();
        itm = new ListItem();
        itm = ddlContractor.Items.FindByText(ch.ContComp.ToString());
        ddlContractor.SelectedValue = itm.Value;
       // ddlContractor.SelectedItem.Text = ch.ContComp.ToString();
        ddlTruckNo.SelectedItem.Text = ch.TruckNo.ToString();
        txtCFT.Text = ch.CFT.ToString();
        txtChallanNo.Text = ch.ChallanNo.ToString();
        ddlDriver.SelectedItem.Text = ch.Driver.ToString();
        ddlCleaner.SelectedItem.Text = ch.Cleaner.ToString();
        ddlMaterial.SelectedItem.Text = ch.MaterialDetail;
        txtTicketNo.Text = ch.TicketNo;
        trImg.Visible = true;
        if (ch.Status != null && ch.Status.Contains("Rejected"))
        {
            trMs.Visible = true;
            lblRejectReason.Text = ch.Comment.ToString();
        }
        imgLogo.ImageUrl = ImageURL(ch.ChallanId.ToString(), Constants.Challan, 1);
        btnCreate.Text = "Update";
    }

    private void CallFillComboBoxes()
    {
        ListCompany(ddlContractor, BusinessClass.CompanyType.Contractor);
        ListCompany(ddlTransport, BusinessClass.CompanyType.Transport);
        ListCompany(ddlSupplier, BusinessClass.CompanyType.Supplier);
        ListTruck();
        ListEmployee();
        ListMaterial();
    }

    private void ListMaterial()
    {
        try
        {
            DataTable dt = new DataTable();
            dt = DataAccessClass.GetMaterial();
            ddlMaterial.DataSource = dt.DefaultView;
            ddlMaterial.DataTextField = "Material";
            ddlMaterial.DataValueField = "MaterialId";
            ddlMaterial.DataBind();
        }
        catch (Exception ex)
        {
        }
    }

    private void ListEmployee()
    {
        try
        {
            DataTable dt = new DataTable();
            dt = DataAccessClass.GetEmployee();
            ddlCleaner.DataSource = dt.DefaultView;
            ddlCleaner.DataTextField = "EmployeeName";
            ddlCleaner.DataValueField = "EmployeeId";
            ddlCleaner.DataBind();
            ddlDriver.DataSource = dt.DefaultView;
            ddlDriver.DataTextField = "EmployeeName";
            ddlDriver.DataValueField = "EmployeeId";
            ddlDriver.DataBind();

        }
        catch (Exception ex)
        {
        }
    }

    private void ListTruck()
    {
        try
        {
            DataTable dt = new DataTable();
            dt = DataAccessClass.GetTruck();
            ddlTruckNo.DataSource = dt.DefaultView;
            ddlTruckNo.DataTextField = "VehicleNo";
            ddlTruckNo.DataValueField = "VehicleId";
            ddlTruckNo.DataBind();
        }
        catch (Exception ex)
        {
        }
    }

    private void ListCompany(DropDownList ddl, BusinessClass.CompanyType companyType)
    {
        try
        {
            DataTable dt = new DataTable();
            dt = DataAccessClass.GetCompany(companyType);
            ddl.DataSource = dt.DefaultView;
            ddl.DataTextField = "CompanyName";
            ddl.DataValueField = "CompanyId";
            ddl.DataBind();
        }
        catch (Exception ex)
        {
        }
    }

    protected void btnCreate_Click(object sender, EventArgs e)
    {
        try
        {
            CallCreateChallan();
        }
        catch (Exception ex)
        {
            ltlError.Text = ex.Message;
            dvError.Visible = true;
        }
    }

    private void CallCreateChallan()
    {
        Challan ch = new Challan();
        ch.ChallanId = Convert.ToInt32(hdnChallanId.Value);
        DateTime dtChallanDate;
        string challDate = "";
        challDate = txtDate.Text; // Request.Form[txtDate.UniqueID];
        if (DateTime.TryParse(challDate, out dtChallanDate))
        {
            ch.ChallanDate = dtChallanDate;
        }
        if (!string.IsNullOrEmpty(txtChallanNo.Text))
        {
            ch.ChallanNo = Convert.ToInt32(txtChallanNo.Text);
        }
        Decimal cft = 0;
        if (decimal.TryParse(txtCFT.Text, out cft))
        {
            ch.CFT = cft;
        }
        int imageSize;
        string imageType;
        Stream imageStream;
        /*  ch.TransportCompId = Convert.ToInt32(ddlTransport.SelectedValue);
          ch.SuppCompId = Convert.ToInt32(ddlSupplier.SelectedValue);
          ch.ContractorCompId = Convert.ToInt32(ddlContractor.SelectedValue);
          ch.DriverId = Convert.ToInt32(ddlDriver.SelectedValue);
          ch.CleanerId = Convert.ToInt32(ddlCleaner.SelectedValue);
          ch.Material = Convert.ToInt32(ddlMaterial.SelectedValue);
          ch.TruckId = Convert.ToInt32(ddlTruckNo.SelectedValue);*/
        ch.SuppComp = ddlSupplier.SelectedItem.Text;
        ch.TransComp = ddlTransport.SelectedItem.Text;
        ch.ContComp = ddlContractor.SelectedItem.Text;
        ch.Driver = ddlDriver.SelectedItem.Text;
        ch.Cleaner = ddlCleaner.SelectedItem.Text;
        ch.MaterialDetail = ddlMaterial.SelectedItem.Text;
        ch.TruckNo = ddlTruckNo.SelectedItem.Text;
        ch.TicketNo = txtTicketNo.Text.Trim();
        imageSize = imgChallan.PostedFile.ContentLength;

        // Gets the Image Type
        imageType = imgChallan.PostedFile.ContentType;

        // Reads the Image stream
        imageStream = imgChallan.PostedFile.InputStream;

        byte[] imageContent = new byte[imageSize];
        int intStatus;
        intStatus = imageStream.Read(imageContent, 0, imageSize);
        ch.ChallanCopy = imageContent;
        ch.UserId = Convert.ToInt32(Session["UserId"]);
        int res = 0;
        res = ch.CreateChallan("Y");
        if (res > 0)
        {
            trMessage.Visible = true;
            trError.Visible = false;
            dvError.Visible = false;
        }
        else
        {
            trMessage.Visible = false;
            trError.Visible = true;
            dvError.Visible = false;
        }
    }
    #endregion

    #region MaterialDetails

    private void CallCreateMaterialPage()
    {
        int mId = 0;

        hdnCOmpId.Value = "0";

        if (Request.QueryString != null && Request.QueryString["MId"] != null)
        {
            mId = Convert.ToInt32(Request.QueryString["MId"].ToString());
            hdnCOmpId.Value = mId.ToString();
            CallUpdateModeMaterial(mId);

        }

    }

    private void CallUpdateModeMaterial(int mId)
    {
        try
        {
            DataTable dt = new DataTable();
            dt = BusinessClass.GetMaterialDetais(0, mId);
            if (dt.Rows.Count > 0)
            {
                lblMaterialStatus.Text = Convert.ToString(dt.Rows[0]["Status"]);
                txtMaterialName.Text = Convert.ToString(dt.Rows[0]["MaterialName"]);
                txtDescription.Text = Convert.ToString(dt.Rows[0]["Description"]);
                trMaterialStatus.Visible = true;
                btnCreateMaterial.Text = "Update";
            }
        }
        catch (Exception ex)
        {
            dvError.Visible = true;
            ltlError.Text = ex.Message;
        }
    }

    protected void btnCreateMaterial_Click(object sender, EventArgs e)
    {
        try
        {
            CreateMaterial();
        }
        catch (Exception ex)
        {
            dvError.Visible = true;
            ltlError.Text = ex.Message;
        }
    }

    private void CreateMaterial()
    {
        int mId = 0;
        mId = Convert.ToInt32(hdnCOmpId.Value);
        int res = 0;
        int userId = Convert.ToInt32(Session["UserId"]);
        res = DataAccessClass.CreateMaterial(mId, txtMaterialName.Text, txtDescription.Text, userId);
        if (res > 0)
        {
            trMessage.Visible = true;
            trError.Visible = false;
        }
        else
        {
            trError.Visible = true;
            trMessage.Visible = false;
        }
    }
    #endregion


}